import pickle,base64
from django_redis import get_redis_connection

def merge_cart_cookie_to_redis(request, user, response):
    """
    登录后合并cookie购物车数据到Redis
    :param request: 本次请求对象，获取 cookie 中的数据
    :param response: 本次响应对象，清除 cookie 中的数据
    :param user: 登录用户信息，获取 user_id
    :return: response
    """
    # 获取cookie中的购物车数据
    cookie_cart = request.COOKIES.get('carts')
    # cookie中没有数据就响应结果
    if not cookie_cart:
        return response
    cart_dict = pickle.loads(base64.b64decode(cookie_cart.encode()))

    new_dict = {}
    new_add = []
    new_remove = []
    # 同步cookie中购物车数据
    for sku_id, item in cart_dict.items():
        new_dict[sku_id] = item['count']

        if item['selected']:
            new_add.append(sku_id)
        else:
            new_remove.append(sku_id)

    # 将new_cart_dict写入到Redis数据库
    redis_conn = get_redis_connection('carts')
    pl = redis_conn.pipeline()
    pl.hmset('carts_%s' % user.id, new_dict)
    # 将勾选状态同步到Redis数据库
    if new_add:
        pl.sadd('selected_%s' % user.id, *new_add)
    if new_remove:
        pl.srem('selected_%s' % user.id, *new_remove)
    pl.execute()

    # 清除cookie
    response.delete_cookie('carts')

    return response




# 1
def get_carts_from_cookies(request):
    """
    获取cookie中的购物车数据
    :param request: 请求对象
    :return: 购物车字典 or {}
    """
    carts_from_cookies = request.COOKIES.get('carts')
    if carts_from_cookies: # "XdnhjgrbewghjrtebABFGNJEKb="
        # 1、先base64解码
        # b'\x56\x78.....'
        cart_dict1 = base64.b64decode(carts_from_cookies.encode())
        # 2、再pickle解码
        cart_dict2 = pickle.loads(cart_dict1)
        return cart_dict2
    else:
        return {}

# 2
def get_cookie_cart_data(cookie_cart):
    """
    使用pickle和base64对购物车字典数据，编码得出存储到cookie中的字符串
    :param cookie_cart: 购物车字典
    :return: 经过pickle和base64编码后的字符串
    """
    # "BNHJBLOhBHYUKNLNJIK="
    return base64.b64encode(
        pickle.dumps(cookie_cart)
    ).decode()


# 3
def get_redis_carts(request):
    user_id = request.user.id
    redis_cart = None
    redis_selected = None

    conn = get_redis_connection('carts')
    # 读取购物车数据
    # redis_cart = {b"14": b"5"} 或者 返回None
    redis_cart = conn.hgetall('carts_%s'%user_id)
    # 读取选中信息
    # redis_selected={b"14"} 后者 返回None
    redis_selected = conn.smembers('selected_%s'%user_id)

    if not redis_cart:
        redis_cart = {} # 如果缓存不存在，则返回空字典
    if not redis_selected:
        redis_selected = set() # 如果缓存不存在则返回空集合

    return redis_cart, redis_selected